package edu.ntu.im.p2ptrade.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import edu.ntu.im.p2ptrade.TransactionManager;
import edu.ntu.im.p2ptrade.Util;
import edu.ntu.im.p2ptrade.entity.DialogRepository;
import edu.ntu.im.p2ptrade.entity.ItemRepository;
import edu.ntu.im.p2ptrade.entity.PeerItemRepository;
import edu.ntu.im.p2ptrade.msg.QueryUser;
import edu.ntu.im.p2ptrade.msg.handle.PeerInfoRepository;

public class InformFrontEnd extends AjaxAction {
	
	private String NO_CHANGE = "no change";

	@Override
	public AjaxResponse execute(HttpServletRequest request) {
		String whosItem = request.getParameter("whosItem");
		String query_user = request.getParameter("QueryUser");
		
		if(query_user != null)
		{
			QueryUser user = new QueryUser();
			Util.transdferMessageToPeer(user.getMessageToTransfer(), query_user);
		}
		
		BackEndInformation info = new BackEndInformation();
		info.dialogs = DialogRepository.getInstance().getDialogs();
		
		info.setCurrentPeers(PeerInfoRepository.getInstance().getAllPeers());
		boolean getAll = Boolean.parseBoolean(request.getParameter("getAll"));
		
        if (whosItem == null && info.getCurrentPeers().size()>0 ){
        	whosItem = info.getCurrentPeers().get(info.getCurrentPeers().keySet().iterator().next()).getName();
		}
       
        if (getAll || PeerItemRepository.getInstance().peerUpdated(whosItem)){
			info.setPeerItems(PeerItemRepository.getInstance().fetchItems(whosItem));
		}
        
		Date now = new Date();
		if (getAll || ItemRepository.getInstance().getLastQueried() == null || ItemRepository.getInstance().getLastQueried().before((ItemRepository.getInstance().getLastModified()))){
			info.setMyItems(ItemRepository.getInstance().fetchItems());
		}
		
		info.getIncoming().addAll(TransactionManager.getInstance().getIncomingReq().values());
		info.getDenied().addAll(TransactionManager.getInstance().getDeniedReq().values());
		info.getAborted().addAll(TransactionManager.getInstance().getAbortedReq().values());
		info.getIssued().addAll(TransactionManager.getInstance().getIssuedReq().values());
		info.getSuccess().addAll(TransactionManager.getInstance().getSuccessReq().values());
		
		return success(info);
	}

}
